function addRightPanelCss(){
    // 创建一个新的<style>元素
    const style = document.createElement('style');
    style.type = 'text/css';

    // 添加CSS规则到<style>元素中
    const cssRules = `
        .panel_top {
            margin: 5px;
            padding: 5px;
            height: 5%;
        }
        
        .panel_main {
            display: flex;
            flex-direction: row;
            /*margin: 5px;*/
            /*padding: 5px;*/
            height: 95%;
        }
        
        .sh-broder {
            background-color: #cdead9;
            /*padding: 10px;*/
            /*margin: 5px;*/
            border: thin solid #8d9956;
            border-width: 2px;
        }
        
        .tabs {
            display: flex;
            width: 100%;
        }
        
        .tab-button {
            display: flex;
            justify-content: center;
            align-items: center;
            flex: 1;
            padding: 10px 20px;
            background-color: #f1f1f1;
            border: 1px solid #ccc;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .tab-button:hover {
            background-color: #ddd;
        }
        
        .tab-content {
            border: 1px solid #ccc;
            /*padding: 20px;*/
            background-color: #fafafa;
            display: flex;
            flex-direction: column;
            /*justify-content: center;*/
            align-items: center;
            width: 100%;
            height: 95%;
            /*overflow: scroll;*/
        }
        
        .preview {
            width: 100%;
            margin: 5px;
            /*padding: 10px;*/
            box-sizing: border-box;
            overflow: auto;
        }
        
        .preview-img-div {
            display: grid;
            /*grid-column-gap: .3rem;*/
            /*-moz-column-gap: .3rem;*/
            column-gap: .3rem;
            /*grid-row-gap: 1rem;*/
            row-gap: .3rem;
            grid-template-columns: repeat(2,auto);
            margin: 5px;
        }
        
        .preview-img {
            /*max-width: 1080px;*/
            width: 100%;
            /*max-height: 100%;*/
            /*margin: 2px;*/
        }
        
        .prelong-img {
            /*max-width: 1080px;*/
            width: 100%;
            /*max-height: 100%;*/
            /*margin: 2px;*/
        }
    `;

    style.appendChild(document.createTextNode(cssRules));
    document.head.appendChild(style);
}

function addRightPanel(){
    // 增加css
    addRightPanelCss();

    /* 右侧容器 */
    var conterDiv = document.createElement("div");
    conterDiv.id = 'preview-con';
    conterDiv.style = `
        display: flex;
        flex-direction: column;
        width: 1000px;
        height: 100%;
    `;

    conterDiv.innerHTML = `
        <div class="panel_top sh-broder">
            <span>书签管理</span>
            <input type="text" name="" id="code-search" style="margin-left: 20px;">
            <input type="number" id="col-num" value="2" min="1" max="3" style="margin-left: 20px; width: 60px;">
            <button id="scroll-top" style="margin-left: 10px;">回到顶部</button>
        </div>
        <div class="panel_main">
            <div class="preview sh-broder">
                <div class="tabs">
                    <div class="tab-button" data-tab="tab1">预览图</div>
                    <div class="tab-button" data-tab="tab2">长预览</div>
                </div>
                <div class="tab-content" id="tab1">
                    <video id="pre-video" controls="" loop="" style="top: 0px; left: 0px; width: 800px;"></video>
                    <div class="preview-img-div" id="one-img"></div>
                </div>
                <div class="tab-content" id="tab2" style="display: none;">
                    <img id="pre-img"/>
                    <div class="preview-img-div" id="long-img"></div>
                </div>
    
    
            </div>
        </div>
    `;

    /* 插入到页面中 */
    var element = document.getElementsByClassName("main")[0];
    if (element){
        element.append(conterDiv);
    }
}

function addPreviewJS(){
    // const folderTree = document.getElementsByClassName('folder-tree')[0];
    // const fileList = document.getElementsByClassName('file-list')[0];
    const previewDiv = document.getElementsByClassName('preview')[0];
    const preImageDiv = document.querySelector('#one-img');
    const longImageDiv = document.querySelector('#long-img');
    const searchTxt = document.getElementById('code-search');
    const colNum = document.getElementById('col-num');
    const scrollContent = document.getElementsByClassName('preview')[0];
    const scrollTopBtn = document.getElementById('scroll-top');

    // Function to preview the bookmark
    function previewBookmark(avcode) {
        // if (titleStr) {
            // titleSpan.textContent = titleStr;
			// document.title = titleStr + ' - JavBook';
        // }
		// selAvUrl = avUrl;
		
		let newCode = formatCode(avcode);
		
		startRequest(avcode, "收藏夹");

		// 增加预览视频
		// let videoSrc = "https://fivetiu.com/" + newCode + "/preview.mp4";
		let videoSrc = "https://fourhoi.com/" + newCode + "/preview.mp4";
		let preVideo = previewDiv.querySelector('#pre-video');
		preVideo.src = videoSrc;

		// 增加预览图
		let imgSrc = "https://pedia-bucket-image.xfuse.fun/covers/" + newCode.toUpperCase() + ".jpg";
		let img = previewDiv.querySelector('#pre-img');
		img.style.width = '100%';
		img.src = imgSrc;


		preImageDiv.innerHTML = '';
		searchFileList_javbus(newCode, 'preview', preImgCallback, finishCallback, infoCallback);


		longImageDiv.innerHTML = '';
		searchFileList(false, avcode, 'longimg', longImgCallback);


        function preImgCallback(ret, imgName){
            if (ret == 1) {
                let avcode_00 = formatCodeFor00(newCode);
                previewUrl = `https://spic.hotoss.com/dmm/digital/video/${avcode_00}/${avcode_00}jp-${imgName}.jpg`;

            } else if (ret == 2) {
                previewUrl = imgName;

            } else if (ret == 0) {
                previewUrl = `http://localhost:10168/preview/${imgName}`;

            } else {
                previewUrl = `http://localhost:10168/preview/error.jpg`;
            }

            let previewImg = document.createElement('img');
            previewImg.classList.add('preview-img');
            previewImg.classList.add('lazyload');
            previewImg.dataset.src = previewUrl;
            previewImg.src = 'http://localhost:10168/longimg/img_loading.jpg';

            preImageDiv.appendChild(previewImg);

        }
		
		// function ciliCallback(ret, rowHtml){
            // if (ret == 0) {
                // ciliPanel.innerHTML += rowHtml;

            // } else {
                // previewUrl = `http://localhost:10168/preview/error.jpg`;
                // let previewImg = document.createElement('img');
                // previewImg.classList.add('preview-img');
                // previewImg.classList.add('lazyload');
                // previewImg.dataset.src = previewUrl;
                // previewImg.src = 'icons/img_loading.jpg';

                // ciliPanel.appendChild(previewImg);
            // }

        // }

        function finishCallback(res) {
            // 监听滚动事件
            lazyLoadImages(scrollContent);

        }
		
        function infoCallback(labelObj) {
            // label_code.textContent = labelObj.lable_code;
            // label_ri.textContent = labelObj.lable_ri;
            // label_zh.textContent = labelObj.lable_zh;
            // label_shic.textContent = labelObj.lable_shic;
            // label_yany.textContent = labelObj.lable_yany;
            // label_jies.textContent = labelObj.lable_jies;

        }


        function longImgCallback(ret, imgName) {
            if (ret == 0) {
                previewUrl = `http://localhost:10168/longimg/${imgName}`;
            } else {
                previewUrl = `http://localhost:10168/longimg/error.jpg`;
            }

            let previewImg = document.createElement('img');
            previewImg.classList.add('prelong-img');
            previewImg.src = previewUrl;

            longImageDiv.appendChild(previewImg);
        }
    }

    function loadImage(img, filePath){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', filePath, true);
        xhr.responseType = 'blob';
        xhr.onload = function(e) {
            if (this.status === 200) {
                var blob = this.response;
                var reader = new FileReader();
                reader.onloadend = function() {
                    // var img = new Image();
                    img.src = reader.result;
                    // document.body.appendChild(img);
                };
                reader.readAsDataURL(blob);
            }
        };
        xhr.send();
    }
	
	function startRequest(avcode, fromStr) {
        let url = `http://localhost:10168/startrequest?avcode=${avcode}&fromstr=${fromStr}`;

        // 使用 fetch 发送 GET 请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析JSON
                return ;
            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('fetch error:', error);
            });

    }

    function searchFileList(isOther, javCode, cls, callback, callFinish = null, callInfo = null) {
        //保存查询关键词参数
        //GM_setValue("115_search_var", `${javId}|${javId2}|${javId3}|${javId4}`);

        let url = null;
        if (cls === 'preview') {
            url = `http://localhost:10168/search?imgcode=${javCode}`;
        } else if (cls === 'longimg') {
            url = `http://localhost:10168/longsearch?imgcode=${javCode}`;
        }
        if (!url) return;

        // 使用 fetch 发送 GET 请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                    callback(-2, null);
                }
                // 解析JSON
                return response.json();
            })
            .then(resultJson => {
                // 处理JSON数据
                if (resultJson.length > 0) {

                    for (let i = 0; i < resultJson.length; i++) {
                        let row = resultJson[i];

                        if (row) {
                            callback(0, row);
                        }
                    }
                    return true;

                }else {
                    throw new Error('Element not found');
                }

            })
            .then(res => {
                if (callFinish) {
                    setTimeout(function () {
                        callFinish(res);
                    }, 500);
                }

            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('fetch error:', error);
                if (isOther && error.message === 'Network response was not ok') {
                    searchFileList_mfinder(javCode, cls, callback, callFinish, callInfo);

                } else if (isOther && error.message === 'Element not found') {
                    searchFileList_mfinder(javCode, cls, callback, callFinish, callInfo);

                } else {
                    callback(-1, null);
                }
            });

    }

    function searchFileList_tor05(javCode, cls, callback, callFinish = null, callInfo = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/tor05/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
            })
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
                // 查询特定的元素
                const imgAaalist = doc.querySelectorAll('#preview-img .glightbox2');
                // 处理查询到的元素
                if (imgAaalist && imgAaalist.length > 0) {
                    console.log('Found element:', imgAaalist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    for (let i = 0; i < imgAaalist.length; i++) {
                        let aaa = imgAaalist[i];
                        callback(2, aaa.href);
                    }
                    return true;

                } else {
                    throw new Error('Element not found');
                }
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                callback(-1, null);

            } else if (error.message === 'Element not found') {
                callback(-1, null);

            } else {
                callback(-1, null);
            }
        });
    }

    function searchFileList_mfinder(javCode, cls, callback, callFinish = null, callInfo = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/mfinder/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
            })
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
				
                const lableObj = {};
                let sss = doc.querySelector('.text-warning');
                if (sss){
                    lableObj.lable_code = sss.textContent;
                }else {
                    lableObj.lable_code = '';
                }

                lableObj.lable_ri = '';

                sss = doc.querySelector('.card-header h3');
                if (sss){
                    lableObj.lable_zh = sss.textContent;
                }else {
                    lableObj.lable_zh = '';
                }

                sss = queryElementBytext(doc, '.col-md-3 p', '作品时长');
                if (sss){
                    lableObj.lable_shic = sss.textContent;
                }else {
                    lableObj.lable_shic = '';
                }

                sss = doc.querySelectorAll('.col-12 .m-title.m-0 a');
                if (sss && sss.length > 0){
                    let arr = Array.from(sss).map(obj => obj.textContent);
                    let str = '';
                    for (let i=0; i<arr.length; i++){
						let item = arr[i];
						if(i !== 0){
							str += '、';
						}
                        str += item;
                    }
                    lableObj.lable_yany = str;
                }else {
                    lableObj.lable_yany = '';
                }

                sss = doc.querySelector('.card-body h5');
                if (sss){
                    sss = sss.parentElement.querySelectorAll('p');
                }
                if (sss && sss.length > 0){
                    lableObj.lable_jies = sss[1].textContent;
                }else {
                    lableObj.lable_jies = '';
                }
                callInfo(lableObj);

                // 查询特定的元素
                const imglist = doc.querySelectorAll('.card-body .screenshot-link img');
                // 处理查询到的元素
                if (imglist && imglist.length > 0) {
                    console.log('Found element:', imglist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    let imgArr = Array.from(imglist);
                    imgArr.sort((a, b) => {
                        let anum = a.src.match(/-(\d{1,2}).jpg/)[1];
                        let bnum = b.src.match(/-(\d{1,2}).jpg/)[1];

                        return anum - bnum;
                    });
                    for (let i = 0; i < imgArr.length; i++) {
                        let img = imgArr[i];
                        imgAddrs = img.src.split('?');
                        callback(2, imgAddrs[0]);
                    }
                    return true;

                } else {
                    throw new Error('Element not found');


                }
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                searchFileList_javbus(javCode, cls, callback, callFinish, callInfo);

            } else if (error.message === 'Element not found') {
                searchFileList_javbus(javCode, cls, callback, callFinish,callInfo);

            } else {
                callback(-1, null);
            }
        });
    }

    function searchFileList_javbus(javCode, cls, callback, callFinish = null, callInfo = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/javbus/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
            })
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
				
				const lableObj = {};
                let sss = doc.querySelector('.col-md-3.info span[style]');
                if (sss){
                    lableObj.lable_code = sss.textContent;
                }else {
                    lableObj.lable_code = '';
                }
				
				sss = doc.querySelector('.container h3');
                if (sss){
                    lableObj.lable_ri = sss.textContent;
                }else {
                    lableObj.lable_ri = '';
                }

                lableObj.lable_zh = '';

                sss = queryElementBytext(doc, '.col-md-3.info p', '長度');
                if (sss){
                    lableObj.lable_shic = sss.textContent;
                }else {
                    lableObj.lable_shic = '';
                }

                sss = doc.querySelectorAll('.col-md-3.info span[onmouseover]');
                if (sss && sss.length > 0){
                    let arr = Array.from(sss).map(obj => obj.textContent.replace(/[\r\n\t]+/g, ''));
                    let str = '';
                    for (let i=0; i<arr.length; i++){
						let item = arr[i];
						if(i !== 0){
							str += '、';
						}
                        str += item;
                    }
                    lableObj.lable_yany = str;
                }else {
                    lableObj.lable_yany = '';
                }

                lableObj.lable_jies = '';
				
                callInfo(lableObj);
				
                // 查询特定的元素
                const imgAaalist = doc.querySelectorAll('#sample-waterfall a');
                // 处理查询到的元素
                if (imgAaalist && imgAaalist.length > 0) {
                    console.log('Found element:', imgAaalist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    for (let i = 0; i < imgAaalist.length; i++) {
                        let aaa = imgAaalist[i];
                        callback(2, aaa.href);
                    }
                    return true;

                } else {
                    throw new Error('Element not found');


                }
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                searchFileList_tor05(javCode, cls, callback, callFinish, callInfo);

            } else if (error.message === 'Element not found') {
                searchFileList_tor05(javCode, cls, callback, callFinish, callInfo);

            } else {
                callback(-1, null);
            }
        });
    }
	
	function searchFileList_javdb(javCode, cls, callback, callFinish = null, callInfo = null, callCili = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/javdb_search/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
				
            }).then(html => {
				const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const movieList = doc.getElementsByClassName('movie-list');
                if (movieList.length > 0) {
                    const firstElement = movieList[0];
                    const firstLink = firstElement.querySelector('a');
                    if (firstLink) {
                        const href = firstLink.getAttribute('href');
						const javdbCode = href.split('/').slice(-1)[0];
                        const fullUrl = 'http://localhost:10168/site/javdb/' + javdbCode + '.html';

                        return fetch(fullUrl);
                    }
                }
				throw new Error('Moive not found');
				
			})
			.then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
				
			})
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
				
				const lableObj = {};
                let sss = doc.querySelector('.first-block span');
                if (sss){
                    lableObj.lable_code = sss.textContent;
                }else {
                    lableObj.lable_code = '';
                }
				
				sss = doc.querySelector('.origin-title');
                if (sss){
                    lableObj.lable_ri = sss.textContent;
                }else {
                    lableObj.lable_ri = '';
                }

                sss = doc.querySelector('.current-title');
                if (sss){
                    lableObj.lable_zh = sss.textContent;
                }else {
                    lableObj.lable_zh = '';
                }

                sss = queryElementBytext(doc, '.panel-block', '時長');
                if (sss){
                    lableObj.lable_shic = sss.textContent;
                }else {
                    lableObj.lable_shic = '';
                }

                sss = doc.querySelectorAll('.panel-block a[href^="/actors"]');
                if (sss && sss.length > 0){
                    let arr = [];
					let arr2 = [];
					for (obj of sss) {
						let nextElement = obj.nextElementSibling;
						if (nextElement && nextElement.textContent === '♀'){
							arr.push(obj.textContent);
						}else if (nextElement && nextElement.textContent === '♂'){
							arr2.push(obj.textContent);
						}
					}
                    let str = '';
                    for (let i=0; i<arr.length; i++){
						let item = arr[i];
						if(i !== 0){
							str += '、';
						}
                        str += item;
                    }
					for (let i=0; i<arr2.length; i++){
						let item = arr2[i];
						if(i == 0){
							str += '++';
						}else{
							str += '、';
						}
                        str += item;
                    }
                    lableObj.lable_yany = str;
                }else {
                    lableObj.lable_yany = '';
                }

                lableObj.lable_jies = '';
				
                callInfo(lableObj);
				
                // 查询特定的元素
                // const imgAaalist = doc.querySelectorAll('.tile-images.preview-images .tile-item');
                // 处理查询到的元素
                // if (imgAaalist && imgAaalist.length > 0) {
                    // console.log('Found element:', imgAaalist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    // for (let i = 0; i < imgAaalist.length; i++) {
                        // let aaa = imgAaalist[i];
                        // callback(2, aaa.href);
                    // }
                    // return true;

                // } else {
                    // throw new Error('Element not found');
                // }
				
				const ciliEles = doc.querySelectorAll('.item.columns');
                if (ciliEles && ciliEles.length > 0){
                    for (ciliEle of ciliEles){
                        let sizeSpan = ciliEle.querySelector('.meta');
                        if (sizeSpan){
                            sizeSpan.textContent = sizeSpan.textContent.replace('B', '').replace('M', 'm').replace(',', '      ------    ')
                        }

                        let tagsSpan = ciliEle.querySelector('.tags');
                        if (tagsSpan){
                            tagsSpan.textContent = '【【' + tagsSpan.textContent + '】】';
                        }

                        let btn = ciliEle.querySelector('.buttons.column button');
                        if (btn){
                            let magnetLink = btn.getAttribute('data-clipboard-text');
                            let imgHtml = '<img src="https://cdn.jsdelivr.net/gh/zxf10608/JavaScript/icon/115logo.ico" class="115offline" data-href='+magnetLink+' style="z-index:9123456789;display:inline-block;cursor:pointer;margin:0px 5px 2px;border-radius:50%;border:0px;vertical-align:middle;outline:none!important;padding:0px!important;height:20px!important;width:20px!important;left:0px!important;top:0px!important;" title="使用115网盘离线下载，右键复制地址\n'+magnetLink+'">';

                            let div = document.createElement('div');
                            div.className = "panel-footer";
                            div.innerHTML += imgHtml;
                            btn.parentElement.appendChild(div);
                        }
                        callCili(0, ciliEle.outerHTML);
                    }
                }else {
                    callCili(-1, null);
                }
				
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                callback(-1, null);

            } else if (error.message === 'Element not found') {
                callback(-1, null);

            } else {
                callback(-1, null);
            }
        });
    }

    // 懒加载逻辑
    function lazyLoadImages(scroolElement) {
        let lazyLoadThrottleTimeout;

        // 检查内容是否在可视窗口内
        function isInViewport(element) {
            let top = element.offsetTop - scrollContent.scrollTop;
            if(top < (window.innerHeight * 2)) {
                return true;
            }

            return false;
        }

        function lazyLoad() {
            if(lazyLoadThrottleTimeout) {
                clearTimeout(lazyLoadThrottleTimeout);
            }

            lazyLoadThrottleTimeout = setTimeout(function() {
                const images = document.querySelectorAll('.lazyload');
                images.forEach(img => {
                    if (img.src.includes('img_loading.jpg') && isInViewport(img)) {
                        // const source = img.getAttribute('data-src');
                        const source = img.dataset.src;
                        img.src = source;
                        // img.removeAttribute('data-src');
                        img.classList.remove('lazyload');
                    }
                });

                if(images.length == 0) {
                    scroolElement.removeEventListener("scroll", lazyLoad);
                    scroolElement.removeEventListener("resize", lazyLoad);
                    scroolElement.removeEventListener("orientationChange", lazyLoad);
                }
            }, 200);
        }

        lazyLoad();
        scroolElement.addEventListener("scroll", lazyLoad);
        scroolElement.addEventListener("resize", lazyLoad);
        scroolElement.addEventListener("orientationChange", lazyLoad);
    }

    function formatCode(code){
        let newCode = code;
        if (code.indexOf('-') == -1){
            let numbers = code.match(/\d+/g);
            let chars = code.match(/[a-zA-Z]+/g);

            if (numbers && chars){
                newCode = chars[0] + "-" + numbers[0];
            }
        }

        return newCode;
    }

    function formatCodeForNone(code){
        let newCode = code;
        if (code.indexOf('-') == -1){
            let numbers = code.match(/\d+/g);
            let chars = code.match(/[a-zA-Z]+/g);

            if (numbers && chars){
                newCode = chars[0] + "%20" + numbers[0];
            }
        }

        return newCode;
    }
	
	function queryElementBytext(doc, flag, searchText){
        let elements = doc.querySelectorAll(flag);
        let filteredElements = Array.from(elements).filter(el => el.textContent.includes(searchText));
        if (filteredElements[0]){
            return filteredElements[0];
        }

        return null;
    }

    searchTxt.addEventListener('input', function (event){
        let searchStr = event.target.value;

        clearTimeout(inputTimer);
        inputTimer = setTimeout(function (){
            // searchBookmarkList(searchStr);
        }, 1000);

    });

    colNum.addEventListener('input', function (event){
        let colNum = event.target.value;

        preImageDiv.style.gridTemplateColumns = `repeat(${colNum},auto)`;
    });

    scrollTopBtn.addEventListener('click', function (event){
        // 滚动到页面顶部的函数
        scrollContent.scrollTo({
            top: 0,
            left: 0,
            behavior: 'smooth' // 可选，平滑滚动
        });
    });

    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');

    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const targetTab = this.getAttribute('data-tab');

            // Hide all tab contents
            tabContents.forEach(content => {
                content.style.display = 'none';
            });

            document.getElementById(targetTab).style.removeProperty('display');

            // Optionally, remove active class from all buttons and add to the clicked button
            tabButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
        });
    });

    function getQueryParam(param) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }

    let avcode = getQueryParam('avcode');
    if (avcode){
        previewBookmark(avcode);
    }

    document.getElementById('list').addEventListener('click', function(event) {
        // 检查点击的是不是 item 元素
        if (event.target && event.target.matches('.label')) {
            // 这里处理点击事件
            console.log('Item clicked:', event.target.textContent);

            let itemTitle = event.target.textContent;
            if (!itemTitle) return;

            let avcode = null;
            let matchs = itemTitle.match(/[a-zA-Z]{2,5}-[0-9]{2,5}/);
            if (matchs[0]){
                avcode = matchs[0];
            }

            if (!avcode) return;

            previewBookmark(avcode.toLowerCase());
        }
    });
}

addRightPanel();
addPreviewJS();